package com.woniuxy.client;
import com.woniuxy.config.AiServiceProperties;
import com.woniuxy.dto.ai.AliyunRequest;
import com.woniuxy.dto.ai.AliyunResponse;
import com.woniuxy.dto.ai.Input;
import com.woniuxy.dto.ai.Message;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

import java.util.Arrays;

@Slf4j
@Component
public class AliyunClient {
    private static final Logger logger = LoggerFactory.getLogger(AliyunClient.class);

    private final WebClient webClient;
    private final AiServiceProperties properties;
    @Autowired
    public AliyunClient(WebClient.Builder webClientBuilder, AiServiceProperties properties){
        this.webClient = webClientBuilder
                .baseUrl(properties.getApiUrl())
                .build();
        this.properties = properties;
    }

    public Mono<String> sendMessage(String message) {
        Message prompt = new Message("system", properties.getSystemPrompt());
        Message userMessage = new Message("user", message);
        AliyunRequest requestPayload  = new AliyunRequest(properties.getModel(),new Input(Arrays.asList(prompt,userMessage)));
        return webClient.post()
                .header(HttpHeaders.AUTHORIZATION, "Bearer " + properties.getApiKey())//设置响应头将密钥放在请求头中
                .contentType(MediaType.APPLICATION_JSON)//设置格式为JSON
                .bodyValue(requestPayload)//设置请求体
                .retrieve()//4. 获取响应
                .bodyToMono(AliyunResponse.class)//5. 将响应体转换为 Mono<AliyunResponse>
                .map(response -> {
                    if (response != null && response.getOutput() != null && response.getOutput().getText() != null) {
                        return response.getOutput().getText();
                    }
                    return "抱歉，AI助手未能生成回答。";
                })
                .doOnError(error -> logger.error("调用阿里云AI API失败: {}", error.getMessage()));
    }
}
